<?php

declare(strict_types=1);

namespace Plugin\Attractions\Broadcast\Process;

use Common\Common;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Process\AbstractProcess;
use Hyperf\Process\Annotation\Process;
use Plugin\Attractions\Broadcast\Constant;
use Plugin\Attractions\Broadcast\Job\BroadcastJob;
use Plugin\Attractions\Broadcast\Repository\Broadcast_devices\BroadcastDevicesRepository;
use Plugin\Attractions\Broadcast\Repository\Broadcast_plans\BroadcastPlansRepository;

#[Process(name: "broadcast-queue-producer")]
class BroadcastProducer extends AbstractProcess
{
    protected int $restartInterval = 10;

    public function isEnable($server): bool
    {
        return env('ENABLE_PROCESS');
    }

    public function handle(): void
    {
        Coroutine::sleep(5);
        $repo = Common::container()->get(BroadcastPlansRepository::class);
        $deviceRepo = Common::container()->get(BroadcastDevicesRepository::class);
        while (true) {
            $time = time();
            $date = explode('-', date('d-w', $time));
            $day = $date[0];
            $week = strval($date[1] + 1);
            $playList = $repo->getPlayList();
            if ($playList) {
                $devices = $deviceRepo->getOnlineByGroup();
                foreach ($playList as $plan) {
                    // 执行次数校验
                    if ($plan['repeat_count'] > 0 && $plan['execution_count'] >= $plan['repeat_count']) {
                        continue;
                    }
                    // 播放日期校验
                    if ($plan['repeat_type'] == Constant::REPEAT_TYPE_WEEK) {
                        $excecutionDay = explode(',', $plan['execution_day']);
                        if (!in_array($week, $excecutionDay)) {
                            continue;
                        }
                    } else if ($plan['repeat_type'] == Constant::REPEAT_TYPE_MONTH) {
                        $excecutionDay = explode(',', $plan['execution_day']);
                        if (!in_array($day, $excecutionDay)) {
                            continue;
                        }
                    }

                    // 时间间隔校验
                    $lastExecutionTime = strtotime($plan['last_execution_time'] ?? '');
                    if ($time - $plan['repeat_interval'] * 60 < $lastExecutionTime ?? 0) {
                        continue;
                    }
                    // 设备
                    $pushDevices = $plan['target_devices'] ?? [];
                    if ($plan['target_groups'] != 0) {
                        foreach ($plan['target_groups'] as $group) {
                            $pushDevices = array_merge($pushDevices, $devices[$group]);
                        }
                    }
                    $pushDevices = array_unique($pushDevices);
                    // 投递任务
                    Common::push_redis_job(new BroadcastJob(
                        [
                            'id' => $plan['id'],
                            'url' => $plan['content_audio_file'],
                            'devices' => $pushDevices,
                            'volume' => $plan['volume_day'],
                            'type' => Constant::PLAN_TYPE_PLAN,
                            'content' => $plan['content_text']
                        ]
                    ), 'broadcast');
                }
            }
            Coroutine::sleep(10);
        }
    }
}
